package in.muton.edushare.pages.cp.backup.restore;

import in.muton.edushare.EduShareSession;
import in.muton.edushare.pages.EduShareBasePage;
import in.muton.edushare.pages.common.EdusharePanel;
import in.muton.edushare.panels.upload.uploadify.UploadifyBehavior;
import in.muton.edushare.panels.upload.uploadify.UploadifyPanel;
import in.muton.edushare.wicket.models.CayenneModel;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;

import org.apache.wicket.ajax.AbstractDefaultAjaxBehavior;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.behavior.IBehavior;
import org.apache.wicket.markup.html.IHeaderResponse;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.repeater.Item;
import org.apache.wicket.markup.repeater.data.GridView;
import org.apache.wicket.markup.repeater.data.IDataProvider;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;

import com.edushare.common.dao.SystemBackupDAO;
import com.edushare.common.util.SystemUtils;
import com.edushare.common.vo.SystemBackup;

public class UploadMediaPanel extends EdusharePanel {

	private static final long serialVersionUID = 1544964014324878485L;
	private File backupDirectory;

	public UploadMediaPanel(String id, final CayenneModel<SystemBackup> bkpModel, final Model<ArrayList<String>> filesModel, final EduShareBasePage page, final RestorePanel restorePanel) {
		super(id, bkpModel, page);
		backupDirectory = new File(SystemUtils.getAbsolutePathFromRelative(bkpModel.getObject().getDirectoryPath()));
		
		IDataProvider<String> data = new IDataProvider<String>(){

			private static final long serialVersionUID = 341259339264082297L;

			public Iterator<? extends String> iterator(int first, int last) {
				return filesModel.getObject().iterator();
			}

			public IModel<String> model(String object) {
				return new Model<String>(object);
			}

			public int size() {
				return filesModel.getObject().size();
			}

			public void detach() {}
			
		};
		
		final Form<Void> form = new Form<Void>("finalizeBkp"){

			private static final long serialVersionUID = -7277811412730628200L;

			@Override
			protected void onSubmit() {
				restorePanel.loadPanel(new StartRestorePanel(RestorePanel.PLACE_HOLDER_PANEL_ID, bkpModel, page, restorePanel));
			}
		};
		form.setVisible(false);
		form.setOutputMarkupPlaceholderTag(true);
		add(form);
		
		Form<Void> cancelForm = new Form<Void>("cancelUpload"){

			private static final long serialVersionUID = 5061366414136959981L;

			@Override
			protected void onSubmit() {
				new SystemBackupDAO(getORMInterface()).delete(bkpModel.getObject());
				getORMInterface().commitAllChanges();
				restorePanel.loadPanel(new ChooseMethodPanel(RestorePanel.PLACE_HOLDER_PANEL_ID, restorePanel.univModel, page, restorePanel));
			}
		};
		add(cancelForm);
		
		final WebMarkupContainer filesList = new WebMarkupContainer("fileList");
		add(filesList);
		filesList.setOutputMarkupId(true);
		
		GridView<String> gv = new GridView<String>("files", data) {
			
			private static final long serialVersionUID = 6741789968966904856L;
			private int uncompleteUpload = 0;

			@Override
			protected void populateEmptyItem(Item<String> item) {
				WebMarkupContainer uploaded = new WebMarkupContainer("uploaded");
				WebMarkupContainer notUploaded = new WebMarkupContainer("notUploaded");
				item.add(uploaded);
				item.add(notUploaded);
				uploaded.setVisible(false);
				notUploaded.setVisible(false);
				item.add(new Label("file", ""));
			}

			@Override
			protected void populateItem(Item<String> item) {
				WebMarkupContainer uploaded = new WebMarkupContainer("uploaded");
				WebMarkupContainer notUploaded = new WebMarkupContainer("notUploaded");
				File f = new File(backupDirectory, item.getModelObject());
				item.add(uploaded);
				item.add(notUploaded);
				if(f.exists()){
					notUploaded.setVisible(false);
				}
				else{
					uploaded.setVisible(false);
					uncompleteUpload++;
				}
				item.add(new Label("file", item.getModelObject()));
				
				if(uncompleteUpload>0)
					form.setVisible(false);
				else
					form.setVisible(true);
				
			}
			
			@Override
			protected void onBeforeRender() {
				uncompleteUpload = 0; //reset it every time before exiting
				super.onBeforeRender();
			}
			
		};
		
		gv.setColumns(2);
		filesList.add(gv);
		
		UploadifyBehavior behav = new UploadifyBehavior(ConfigUploadProcessPage.class, EduShareSession.get().getId());
		behav.setFileDesc("*.bz.*");
		behav.setFileExt("*.bz.*");
		behav.setScriptData("'bkpId':'"+bkpModel.getObject().getSystemBackupId()+"'");
		behav.setSizeLimit(""+ 1000*1000*1000);
		add(new UploadifyPanel("mediDiv",page, behav));
		
		IBehavior repaintFileList = new AbstractDefaultAjaxBehavior() {
			
			private static final long serialVersionUID = 3969459694177808439L;

			@Override
			protected void respond(AjaxRequestTarget target) {
				target.addComponent(filesList);
				target.addComponent(form);
			}
			
			@Override
			public void renderHead(IHeaderResponse response) {
				super.renderHead(response);
				CharSequence callback = getCallbackScript();
				response.renderJavascript("function uploadCompleted(){ "+ callback +"}", "customUploadFinished");
			}
		};
		
		add(repaintFileList);
	}

}
